package com.example.music.fragment

import android.animation.ObjectAnimator
import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.animation.LinearInterpolator
import android.widget.ImageButton
import android.widget.ImageView
import android.widget.SeekBar
import android.widget.TextView
import androidx.fragment.app.Fragment
import com.bumptech.glide.Glide
import com.example.music.MainActivity
import com.example.music.R
import com.example.music.model.Song
import com.example.music.service.MusicService
import java.util.concurrent.TimeUnit

class MusicPlayFragment : Fragment(), MusicService.OnPlaybackStateChangeListener, MainActivity.OnProgressUpdateListener {
    private lateinit var albumCover: ImageView
    private lateinit var songTitleText: TextView
    private lateinit var artistNameText: TextView
    private lateinit var seekBar: SeekBar
    private lateinit var currentTimeText: TextView
    private lateinit var totalTimeText: TextView
    private lateinit var playPauseButton: ImageButton
    private lateinit var prevButton: ImageButton
    private lateinit var nextButton: ImageButton
    private var rotationAnimator: ObjectAnimator? = null
    private val handler = Handler(Looper.getMainLooper())
    private val updateProgressRunnable = object : Runnable {
        override fun run() {
            (activity as? MainActivity)?.let { activity ->
                if (activity.musicService.isPlaying()) {
                    val duration = activity.musicService.getDuration()
                    val position = activity.musicService.getCurrentPosition()
                    onProgressUpdated(position, duration)
                }
            }
            handler.postDelayed(this, 1000)
        }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.activity_music_detail, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initViews(view)
        setupListeners()
        syncWithMainActivity()
    }

    private fun initViews(view: View) {
        albumCover = view.findViewById(R.id.albumCover)
        songTitleText = view.findViewById(R.id.songTitle)
        artistNameText = view.findViewById(R.id.artistName)
        seekBar = view.findViewById(R.id.seekBar)
        currentTimeText = view.findViewById(R.id.currentTime)
        totalTimeText = view.findViewById(R.id.totalTime)
        playPauseButton = view.findViewById(R.id.playPauseButton)
        prevButton = view.findViewById(R.id.prevButton)
        nextButton = view.findViewById(R.id.nextButton)

        view.findViewById<androidx.appcompat.widget.Toolbar>(R.id.toolbar).visibility = View.GONE
    }

    private fun setupListeners() {
        playPauseButton.setOnClickListener {
            (activity as? MainActivity)?.let { activity ->
                if (activity.musicService.isPlaying()) {
                    activity.musicService.pause()
                } else {
                    val currentSong = activity.getCurrentPlaybackState().first
                    if (currentSong?.id != activity.musicService.getCurrentSong()?.id) {
                        currentSong?.let { activity.playSong(it) }
                    } else {
                        activity.musicService.start()
                    }
                }
                updatePlayPauseButton(activity.musicService.isPlaying())
            }
        }

        prevButton.setOnClickListener {
            (activity as? MainActivity)?.playPrevious()
        }

        nextButton.setOnClickListener {
            (activity as? MainActivity)?.playNext()
        }

        seekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                if (fromUser) {
                    (activity as? MainActivity)?.let { activity ->
                        activity.musicService.seekTo(progress)
                        updateTimeText(progress, seekBar?.max ?: 0)
                    }
                }
            }
            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })
    }

    private fun updateUI(song: Song?) {
        song?.let {
            songTitleText.text = it.name
            it.artist?.let { artist ->
                artistNameText.visibility = View.VISIBLE
                artistNameText.text = artist
            } ?: run {
                artistNameText.visibility = View.GONE
            }

            Glide.with(this)
                .load(it.coverUrl)
                .error(R.drawable.default_music_cover)
                .into(albumCover)
        }
    }

    private fun updatePlayPauseButton(isPlaying: Boolean) {
        playPauseButton.setImageResource(
            if (isPlaying) R.drawable.ic_pause else R.drawable.ic_play
        )
    }

    private fun updatePlaybackState(song: Song?, isPlaying: Boolean) {
        updateUI(song)
        updatePlayPauseButton(isPlaying)
        if (isPlaying) {
            startRotationAnimation()
        } else {
            rotationAnimator?.pause()
        }
    }

    private fun startRotationAnimation() {
        rotationAnimator?.cancel()
        rotationAnimator = ObjectAnimator.ofFloat(albumCover, View.ROTATION, albumCover.rotation, albumCover.rotation + 360f).apply {
            duration = 20000 // 20秒转一圈
            repeatCount = ObjectAnimator.INFINITE
            interpolator = LinearInterpolator()
            start()
        }
    }

    private fun startProgressUpdate() {
        handler.removeCallbacks(updateProgressRunnable)
        handler.post(updateProgressRunnable)
    }

    private fun stopProgressUpdate() {
        handler.removeCallbacks(updateProgressRunnable)
    }

    private fun syncWithMainActivity() {
        (activity as? MainActivity)?.let { activity ->
            activity.musicService.setPlaybackStateChangeListener(this)
            activity.setProgressUpdateListener(this)
            
            val state = activity.getCurrentPlaybackState()
            updateUI(state.first)
            updatePlaybackState(state.first, state.third)
            
            val duration = activity.musicService.getDuration()
            val position = activity.musicService.getCurrentPosition()
            onProgressUpdated(position, duration)
            
            if (state.third) {
                startRotationAnimation()
                startProgressUpdate()
            } else {
                rotationAnimator?.pause()
                stopProgressUpdate()
            }
        }
    }

    override fun onPlaybackStateChanged(song: Song?, isPlaying: Boolean) {
        view?.post {
            try {
                updatePlaybackState(song, isPlaying)
                if (isPlaying) {
                    startRotationAnimation()
                    startProgressUpdate()
                } else {
                    rotationAnimator?.pause()
                    stopProgressUpdate()
                }
            } catch (e: Exception) {
                Log.e("MusicPlayFragment", "更新播放状态失败", e)
            }
        }
    }

    override fun onProgressUpdated(position: Int, duration: Int) {
        view?.post {
            try {
                if (duration > 0) {
                    seekBar.max = duration
                    seekBar.progress = position
                    updateTimeText(position, duration)
                }
            } catch (e: Exception) {
                Log.e("MusicPlayFragment", "更新进度失败", e)
            }
        }
    }

    private fun updateTimeText(current: Int, total: Int) {
        currentTimeText.text = formatTime(current)
        totalTimeText.text = formatTime(total)
    }

    private fun formatTime(millis: Int): String {
        val minutes = TimeUnit.MILLISECONDS.toMinutes(millis.toLong())
        val seconds = TimeUnit.MILLISECONDS.toSeconds(millis.toLong()) -
                TimeUnit.MINUTES.toSeconds(minutes)
        return String.format("%02d:%02d", minutes, seconds)
    }

    override fun onDestroyView() {
        super.onDestroyView()
        rotationAnimator?.cancel()
        rotationAnimator = null
        stopProgressUpdate()
        (activity as? MainActivity)?.let { activity ->
            activity.setProgressUpdateListener(null)
            activity.musicService.setPlaybackStateChangeListener(activity)
        }
    }

    override fun onResume() {
        super.onResume()
        (activity as? MainActivity)?.setPlayerControlVisibility(false)
        syncWithMainActivity()
    }

    override fun onPause() {
        super.onPause()
        rotationAnimator?.pause()
        stopProgressUpdate()
        (activity as? MainActivity)?.let { activity ->
            activity.setProgressUpdateListener(null)
            activity.musicService.setPlaybackStateChangeListener(activity)
        }
    }
} 